package com.hhq.system.plugin.mybatis.handler;

import com.baomidou.mybatisplus.extension.plugins.handler.TenantLineHandler;
import com.hhq.system.config.property.TenantProperties;
import com.hhq.system.security.util.SecurityUtils;
import com.hhq.system.security.util.TenantContextHolder;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.LongValue;

import java.util.List;

/**
 * <p>Description: 多租户处理器 </p>
 *
 * @author : xiaodong.yang
 * @date : 2024/6/26 15:04
 */
public class MultiTenantHandler implements TenantLineHandler {
    private final TenantProperties properties;

    private final TenantContextHolder tenantContextHolder;

    public MultiTenantHandler(TenantProperties properties, TenantContextHolder tenantContextHolder) {
        this.properties = properties;
        this.tenantContextHolder = tenantContextHolder;
    }

    @Override
    public Expression getTenantId() {
        //实际应该从用户信息中获取
        if (SecurityUtils.getUser() != null) {
            Long tenantId = tenantContextHolder.getTenant();
            if (null != tenantId) {
                return new LongValue(tenantId);
            } else {
                return new LongValue("0");
            }
        }
        return new LongValue("0");
    }

    /**
     * 获取租户字段名,默认字段名叫: tenant_id
     *
     * @return 租户字段名
     */
    @Override
    public String getTenantIdColumn() {
        return properties.getColumn();
    }

    /**
     * 根据表名判断是否忽略拼接多租户条件
     * <p>
     * 默认都要进行解析并拼接多租户条件
     *
     * @param tableName 表名
     * @return 是否忽略, true:表示忽略，false:需要解析并拼接多租户条件
     */
    @Override
    public boolean ignoreTable(String tableName) {

        //忽略指定用户对租户的数据过滤
        List<String> ignoreLoginNames = properties.getIgnoreLoginNames();
        if (null != SecurityUtils.getUser()) {
            String loginName = SecurityUtils.getUser().getUsername();
            if (null != ignoreLoginNames && ignoreLoginNames.contains(loginName)) {
                return true;
            }
        }

        //忽略指定表对租户数据的过滤
        List<String> ignoreTables = properties.getIgnoreTables();
        if (null != ignoreTables && ignoreTables.contains(tableName)) {
            return true;
        }

        return false;
    }
}
